/**
 * 全民营销首页
 */
define(function (require, exports, module) {
    var $ = require("jquery");
    var util = require("util");
    var ui = require("ui");
    var tmpl = require("tmpl");
    var storage = require("storage");
    var popAd = require('/static_public/js/pop1Ad1');

    require('permission');
    require('authorize');
    require('global');
    require("/static_public/js/lib/highcharts.cmd");


    var api_prefix = G_CONFIG["api_prefix"] + "/qmyx/index/"; //api前缀

    var Home = {
        token: "",
        cityMode: 1, //城市列表类型，0为标准，1为自定义(默认)
        cityProjs: null,
        selProjIds: [], //选中的项目id列表
        init: function () {
            this.token = util.getToken();
            this.lastProjsKey = this.token + "_last_proj_ids";

            this.bindEvent();
            this.getLastProjIds();
            this.showSelProjCount();
            this.querySummaryData();
            this.showChart();
            this.setClick();
        },
        getLastProjIds: function () {
            var obj = storage.get({key: this.lastProjsKey});
            if (obj.value === null) {
                this.selProjIds = "all";
            } else {
                this.selProjIds = $.parseJSON(obj.value);
            }
        },
        saveProjIds: function () {
            storage.set({key: this.lastProjsKey, value: JSON.stringify(this.selProjIds)});
        },
        showSelProjCount: function () {
            if (this.selProjIds == "all") {
                $("#sel_proj_txt").html('全部项目');
            } else {
                $("#sel_proj_txt").html('已选 <span class="c-red">' + this.selProjIds.length + "</span> 个项目");
            }
        },
        bindEvent: function () {
            var _this = this;
            $("#btn_change_proj").on("click", function (e) {
                e.preventDefault();
                if (_this.cityProjs == null) {
                    _this.queryCityProjs();
                } else {
                    _this.showChangeProj();
                }
            });
        },
        showChangeProj: function () {
            var _this = this;
            if (!_this.projDialog) {
                var html = tmpl("sel_proj_tmpl", {cityMode: this.cityMode, list: _this.cityProjs});
                require.async("dialogplus", function (dialog) {
                    _this.projDialog = dialog({
                        title: "切换",
                        content: html,
                        width: 700,
                        height: 480,
                        onshow: function () {
                            _this.initSelProj();
                        },
                        ok: function () {
                            var cbs = $("#ul_proj_list input:checkbox[data_type='project']").filter(":checked");
                            var projIds = [];
                            cbs.each(function () {
                                projIds.push($(this).attr("id"));
                            });
                            if (JSON.stringify(projIds) !== JSON.stringify(_this.selProjIds)) {
                                _this.selProjIds = projIds;
                                _this.showSelProjCount();
                                _this.saveProjIds();
                                _this.querySummaryData();
                                _this.showChart();
                            }
                            this.close();
                            return false;
                        },
                        cancel: function () {
                            this.close();
                            return false;
                        }
                    });
                    _this.projDialog.showModal();
                });
            } else {
                _this.projDialog.showModal();
            }
        },
        initSelProj: function () {
            if (!this.initedSelProj) {
                var _this = this;
                $("#ul_proj_list").on("click", ".citytree-toggler", function () {
                    $(this).parent().parent().toggleClass("citytree-closed");
                });
                $("#ul_proj_list").on("click", ".js-district-name", function () {
                    $(this).find(".citytree-arrow").toggleClass("citytree-arrow-hide");
                    $(this).parent().next().toggle();
                });
                $("#cb_all").on("click", function (e) {
                    $("#ul_proj_list").find("input:checkbox").prop("checked", this.checked);
                    _this.setSelProjCount();
                });
                var $cblist = $("#ul_proj_list").find("input:checkbox");
                $cblist.on("change", function (e) {
                    var $li = $(this).closest("li");
                    $li.find("input:checkbox").prop("checked", this.checked);
                    if (!this.checked) {
                        $("#cb_all").prop("checked", false);
                    } else if ($cblist.length == $cblist.filter(":checked").length) {
                        $("#cb_all").prop("checked", true);
                    }
                    _this.setSelProjCount();
                });
                //级联选中
                $("#ul_proj_list li").on("click", function (e) {
                    if (e.target.type == "checkbox") {
                        var $el = $(e.currentTarget);
                        var $li = $el.closest("li.citytree-li");
                        var child_cbs = $li.find("ul input:checkbox");
                        if (child_cbs.length == child_cbs.filter(":checked").length) {
                            $li.find(">.citytree-element input:checkbox").prop("checked", true);
                        } else {
                            $li.find(">.citytree-element input:checkbox").prop("checked", false);
                        }
                    }
                });
                if (this.selProjIds == "all") {
                    $("#cb_all").trigger("click");
                } else {
                    $("#proj_count").text(this.selProjIds.length);
                    $.each(this.selProjIds, function (i, id) {
                        var $proj = $("#" + id);
                        //将选中的项目节点展开
                        $proj.click().closest(".citytree-area").show().prev().find(".citytree-arrow").removeClass("citytree-arrow-hide");
                    });
                    if ($cblist.length == $cblist.filter(":checked").length) {
                        $("#cb_all").prop("checked", true);
                    }
                }
                this.initedSelProj = true;
            }
        },
        setSelProjCount: function () {
            var cbs = $("#ul_proj_list input:checkbox[data_type='project']").filter(":checked");
            $("#proj_count").text(cbs.length);
        },
        //查询城市下的项目列表
        queryCityProjs: function () {
            var url = G_CONFIG["api_prefix"] + "/qmyx/city-regional/get-city-list";
            util.myAjax({
                url: url,
                type: "GET",
                cache: false,
                context: this,
                success: function (json) {
                    if (json.retCode == 0) {
                        this.cityMode = json.city_mode;
                        this.cityProjs = this.filterProjs(json.data);
                        this.showChangeProj();
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                },
                complete: function () {
                    ui.removeLoading();
                }
            });
            ui.loading();
        },
        //过滤掉没有项目的数据
        filterProjs: function (list) {
            var ret = [];
            if (this.cityMode == "0") { //标准模式
                $.each(list, function (i, group) {
                    var citys = [];
                    $.each(group.children, function (j, city) {
                        var hasProj = false;
                        var districts = [];
                        $.each(city.children, function (k, district) {
                            if (district.children && district.children.length > 0) {
                                hasProj = true;
                                districts.push(district);
                            }
                        });
                        city.children = districts;
                        if (hasProj) {
                            citys.push(city);
                        }
                    });
                    group.children = citys;
                    if (citys.length > 0) {
                        ret.push(group);
                    }
                });
            } else {
                $.each(list, function (i, city) {
                    var hasProj = false;
                    var districts = [];
                    $.each(city.children, function (k, district) {
                        if (district.children && district.children.length > 0) {
                            hasProj = true;
                            districts.push(district);
                        }
                    });
                    city.children = districts;
                    if (hasProj) {
                        ret.push(city);
                    }
                });
            }
            return ret;
        },
        //查询统计数据
        querySummaryData: function () {
            var url = api_prefix + 'get-summary-data';
            if (this.selProjIds == "all") {
                var data = {
                    proj_ids: JSON.stringify(["all"])
                };
            } else {
                var data = {
                    proj_ids: JSON.stringify(this.selProjIds)
                };
            }
            util.myAjax({
                url: url,
                type: "POST",
                data: data,
                context: this,
                success: function (json) {
                    if (json.retCode == 0) {
                        var brokerage = json.data.brokerage;
                        var $brokerage = $("#brokerage");
                        $brokerage.find(".js-offered").text(util.formatNumber(brokerage.offered, 2));
                        $brokerage.find(".js-unapproval").text(util.formatNumber(brokerage.unapproval, 2));
                        $brokerage.find(".js-approval").text(util.formatNumber(brokerage.approval, 2));

                        var customer = json.data.customer;
                        var $customer = $("#customer");
                        $customer.find(".js-audited").text(util.formatNumber(customer.audited, 0));
                        $customer.find(".js-pending").text(util.formatNumber(customer.pending, 0));
                        $customer.find(".js-yesterday").text(util.formatNumber(customer.yesterday, 0));

                        var broker = json.data.broker;
                        var $broker = $("#broker");
                        $broker.find(".js-audited").text(util.formatNumber(broker.audited, 0));
                        $broker.find(".js-pending").text(util.formatNumber(broker.pending, 0));
                        $broker.find(".js-yesterday").text(util.formatNumber(broker.yesterday, 0));
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                },
                complete: function () {
                    ui.removeLoading();
                }
            });
            ui.loading();
        },

        // 设置是否能点击
        setClick: function () {
            var url = G_CONFIG["api_prefix"] + "common/my-applicationto-project/get-applicationto-project";
            util.myAjax({
                url: url,
                type: "GET",
                success: function (json) {
                    if (json.retCode == 0) {
                        if (json.data["5003"] && json.data["5008"]) {
                            return
                        } else if (json.data["5003"]) {
                            Home.alertTips("5008");
                        } else if (json.data["5008"]) {
                            Home.alertTips("5003");
                        } else {
                            Home.alertTips("5003");
                            Home.alertTips("5007");
                            Home.alertTips("5008");
                        }
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                }
            });

        },
        alertTips: function (code) {
            var selector = "a[data-code='" + code + "']";
            $(selector).attr("href", "javascript:void(0)");
            $(selector).on("click", function () {
                util.alert("当前公众号没有绑定此应用");
            })
        },

        // =======================图表数据结构 start======================================
        dataDefault: {
            colors: ["#00a2ff"],
            title: {
                text: ''
            },
            subtitle: {
                text: ''
            },
            lang: {
                noData: "暂无数据"
            },
            xAxis: {
                tickWidth: 0,
                labels: {
                    step: 5,
                    staggerLines: 1,
                    style: {color: '#333333'}
                }
                // categories: ['0时', '1时', '2时', '3时', '4时', '5时', '6时', '7时', '8时', '9时', '10时', '11时', '12时', '13时', '14时', '15时', '16时', '17时', '18时', '19时', '20时', '21时', '22时', '23时','24时']
            },
            yAxis: {
                floor: 0,
                title: {
                    text: ''
                },
                labels: {
                    step: 1,
                    style: {color: '#333333'}
                }
            },
            tooltip: {
                valueSuffix: ''
            },
            legend: {
                enabled: false
            },
            credits: { // 版权
                enabled: false
            },
            series: []/*[{
             name: '项目1',
             color: 'red',
             data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
             }, {
             name: '项目2',
             data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
             }]*/
        },
        showChart: function () {
            if (this.selProjIds !== "all") {
                this.getChart(this.selProjIds)
            } else {
                this.getCityPro();
            }
        },
        getChart: function (proj) {
            var proj = JSON.stringify(proj);
            var url = G_CONFIG["api_prefix"] + "olap/cst-incr-trend/get-all-kh-count-info&projguids=" + proj;
            util.myAjax({
                url: url,
                type: "get",
                cache: false,
                success: function (json) {
                    if (json.data.length > 0) {
                        Home.loadChart(json.data);
                    } else {
                        $("#graphic_content").find("no-data").removeClass("none")
                    }
                }
            });
        },
        // 创建图表
        loadChart: function (data) {
            var categories = [];
            var series = [];
            var len = data.length;
            for (var i = 0; i < len; i++) {
                categories.push(data[i]["xdate"]);
                series.push(data[i]["count"]);
            }
            // 修改默认值
            Home.dataDefault.xAxis.categories = categories;
            Home.dataDefault.series = [{"name": "客户数", "data": series}];
            $("#graphic").highcharts(Home.dataDefault);
        },

        //获取城市下的项目
        getCityPro: function () {
            var arr = [];
            var url = G_CONFIG["api_prefix"] + "/qmyx/city-regional/get-city-list";
            util.myAjax({
                url: url,
                type: "GET",
                cache: false,
                context: this,
                success: function (json) {
                    if (json.retCode == 0) {
                        this.getProId(json.data);
                        this.getChart(this.proId);
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                }
            });
        },
        //获取城市下的项目id
        proId: [],
        getProId: function (data) {
            for (var i = 0, len = data.length; i < len; i++) {
                if (data[i]["data_type"] === "project") {
                    this.proId.push(data[i]["id"]);
                }
                if (data[i]["children"] && data[i]["children"].length > 0) {
                    this.getProId(data[i]["children"])
                }
            }
        }
    };

    Home.init();

    popAd.run({
        key: 'showed_self_check',
        html: '<a class="js_close_btn" target="_blank" href="http://help.myscrm.com.cn/details.html?category=%E6%96%B0%E6%89%8B%E5%AD%A6%E5%A0%82&sub=%E8%BF%90%E8%90%A5%E7%8E%A9%E8%B5%B7%E6%9D%A5&articalId=272">' +
        '<img style="width:450px;height:329px;" src="http://img-dev.myscrmimg.cn/projects/qmyx/public/images/pic/ad_self_check.png" usemap="#Map">' +
        '</a>' +
        '<map name="Map" id="Map">' +
        '<area shape="rect" coords="400,10,450,70" class="js_close_btn" href="javascript:;"/>' +
        '<area shape="rect" class="js_close_btn" coords="150,250,300,300" target="_blank" href="http://help.myscrm.com.cn/details.html?category=%E6%96%B0%E6%89%8B%E5%AD%A6%E5%A0%82&sub=%E8%BF%90%E8%90%A5%E7%8E%A9%E8%B5%B7%E6%9D%A5&articalId=272"  style="cursor: pointer"/>' +
        '</map>',
        expires: 30
    });

    module.exports = Home;
});